<?php


namespace app\admin\controller;

use app\common\controller\AdminController;
use Fairy\HttpCrontabService;
use think\App;
use utils\MyToolkit;

/**
 * 定时任务
 * Class SystemCrontab
 * @package app\admin\controller
 * @ControllerAnnotation(title="定时任务管理")
 */
class SystemCrontab extends AdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            try {
                $response = $this->crontab(HttpCrontabService::getCrontabIndexPath() . '?' . $this->request->query());
                $data = [
                    'code' => 0,
                    'msg' => '',
                    'count' => $response['data']['count'],
                    'data' => $response['data']['list'],
                ];
            } catch (\Exception $e) {
                $data = [
                    'code' => 1,
                    'msg' => $e->getMessage(),
                    'count' => 0,
                    'data' => [],
                ];
            }
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            $bool = true;
            try {
                $response = $this->crontab(HttpCrontabService::getCrontabAddPath(), $post);
            } catch (\Exception $e) {
                $bool = false;
            }
            $bool ? $this->success('保存成功') : $this->error($e->getMessage());
        }

        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
        $rule = [
            'id|ID' => 'require',
            'field|字段' => 'require',
            'value|值' => 'require',
        ];
        $this->validate($post, $rule);
        $bool = true;
        try {
            $this->crontab(HttpCrontabService::getCrontabModifyPath(), ['id' => $post['id'], 'field' => $post['field'], 'value' => $post['value']]);
        } catch (\Exception $e) {
            $bool = false;
        }
        $bool ? $this->success('修改成功') : $this->error($e->getMessage());
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $save = true;
        try {
            $response = $this->crontab(HttpCrontabService::getCrontabDeletePath(), ['id' => is_array($id) ? join(',', $id) : $id]);
        } catch (\Exception $e) {
            $save = false;
        }
        $save ? $this->success('删除成功') : $this->error($e->getMessage());
    }

    /**
     * @NodeAnotation(title="日志")
     */
    public function flow()
    {
        $id = $this->request->get('id');
        if ($this->request->isAjax()) {
            try {
                $response = $this->crontab(HttpCrontabService::getCrontabFlowPath() . '?' . $this->request->query());
                $data = [
                    'code' => 0,
                    'msg' => 'OK',
                    'count' => $response['data']['count'],
                    'data' => $response['data']['list'],
                ];
            } catch (\Exception $e) {
                $data = [
                    'code' => 1,
                    'msg' => $e->getMessage(),
                    'count' => 0,
                    'data' => [],
                ];
            }

            return json($data);
        }

        return $this->fetch('', ['sid' => $id]);
    }

    /**
     * @NodeAnotation(title="重启")
     */
    public function reload($id)
    {
        $bool = true;
        try {
            $this->crontab(HttpCrontabService::getCrontabReloadPath(), ['id' => $id]);
        } catch (\Exception $e) {
            $bool = false;
        }
        $bool ? $this->success('重启成功') : $this->error($e->getMessage());
    }

    /**
     * @NodeAnotation(title="ping")
     */
    public function ping()
    {
        $code = 1;
        try {
            $this->crontab(HttpCrontabService::getCrontabPingPath());
        } catch (\Exception $e) {
            $code = 0;
        }

        return json(['code' => $code]);
    }

    /**
     * @param $path
     * @param string $data
     * @return mixed
     * @throws \Exception
     */
    protected function crontab($url, $data = '')
    {
        try {
            $response = MyToolkit::curlRequest($url, $data, ['key: Q85gb1ncuWDsZTVoAEvymrNHhaRtp73M']);
            $data = json_decode($response, true);
            if ($data['code'] !== 200) {
                throw new \Exception($data['msg']);
            }
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }
}
